#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project:     rest_flask
# @File:        wiki_serv.py
# @Author:      Fan GuiChuan
# @Date:        2025/7/4 11:16
# @Version:     Python3.7
# @Description:
import datetime

from flask import request
from app.models.models import db, WikiInfo

class WikiServ:
    def __init__(self, logger):
        self.logger = logger
      
    def add_wiki(self):
        """
        添加Wiki
        """
        try:
            wiki_data = request.json
            self.logger.debug(f"add wiki data: {wiki_data}")
            wiki_name = (wiki_data.get('wiki_name') or '').strip()
            wiki_content = wiki_data.get('wiki_content', '')
            if not wiki_name:
                return False, 'Wiki名不能为空。'
            # 检查是否存在项目名称
            existing = WikiInfo.query.filter_by(wiki_name=wiki_name).first()
            if existing:
                return False, 'Wiki名称已存在，请选择其他Wiki名称。'

            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            new_wiki = WikiInfo(wiki_name=wiki_name,
                                wiki_content=wiki_content,
                                update_time=current_time,
                                create_time=current_time)
            db.session.add(new_wiki)
            db.session.commit()
            return True, new_wiki.wiki_id
        except Exception as e:
            self.logger.exception(str(e))
            return False, str(e)
    
    def get_wiki_tree(self):
        """
        获取wiki树
        """
        try:
            wikis = WikiInfo.query.all()
            result = []
            for wiki in wikis:
                result.append(wiki.to_dict())
            return True, result
        except Exception as e:
            self.logger.exception(str(e))
            return False, str(e)

    def get_wiki_content(self):
        """
        获取wiki内容
        """
        try:
            req_data = request.json
            wiki_id = req_data.get('wiki_id')
            if not wiki_id:
                return False, '获取Wiki ID失败'
            wiki_info = WikiInfo.query.get(wiki_id)
            self.logger.debug(f"wiki content: {wiki_info.wiki_content}")
            return True, wiki_info.wiki_content
        except Exception as e:
            self.logger.exception(str(e))
            return False, str(e)

    def update_wiki_content(self):
        """
        更新wiki内容
        """
        try:
            req_data = request.json
            wiki_id = req_data.get('wiki_id')
            wiki_content = req_data.get('wiki_content')
            if not wiki_id:
                return False, '获取Wiki ID失败'

            if wiki_content is None:
                return False, '获取Wiki内容失败'
            wiki = WikiInfo.query.get(wiki_id)
            if not wiki:
                return False, 'Wiki不存在'
            for key, value in req_data.items():
                if hasattr(wiki, key):
                    setattr(wiki, key, value)
            db.session.commit()
            return True, {
                'wiki_id': wiki_id
            }
        except Exception as e:
            self.logger.exception(str(e))
            return False, str(e)

    def delete_wiki(self):
        """
        删除Wiki
        """
        try:
            req_data = request.json
            self.logger.debug(f"delete wiki: {req_data}")
            deleted_count = db.session.query(WikiInfo).filter(WikiInfo.wiki_id.in_(req_data)).delete()
            db.session.commit()
            return True, {
                "delete_count": deleted_count
            }
        except Exception as e:
            self.logger.exception(str(e))
            return False, str(e)